<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" 
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布书籍 - 校园二手书交易平台</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <style>
        .publish-form {
            background-color: #f8f9fa;
            padding: 30px;
            border-radius: 5px;
        }
        .publish-title {
            margin-bottom: 30px;
            text-align: center;
        }
        .image-preview {
            max-width: 100%;
            max-height: 200px;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .navbar-nav .nav-item {
            margin-right: 15px;
        }
        .footer {
            background-color: #343a40;
            color: white;
            padding: 30px 0;
            margin-top: 50px;
        }
        .required-field::after {
            content: "*";
            color: red;
            margin-left: 4px;
        }
        .upload-tab-content {
            min-height: 100px;
            padding: 15px 0;
        }
        #uploadProgress {
            height: 10px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" th:href="@{/}">校园二手书交易平台</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav mr-auto">
                    <li class="nav-item">
                        <a class="nav-link" th:href="@{/}"><i class="fas fa-home"></i> 首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" th:href="@{/book/list}"><i class="fas fa-book"></i> 书籍列表</a>
                    </li>
                    <li class="nav-item active">
                        <a class="nav-link" th:href="@{/book/publish}"><i class="fas fa-plus"></i> 发布书籍</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" th:href="@{/book/my-books}">我的书籍</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" th:href="@{/order/my-orders}">我的订单</a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown">
                            <span sec:authentication="name"></span>
                        </a>
                        <div class="dropdown-menu dropdown-menu-right">
                            <a class="dropdown-item" th:href="@{/user/profile}">个人信息</a>
                            <a class="dropdown-item" th:href="@{/user/change-password}">修改密码</a>
                            <div class="dropdown-divider"></div>
                            <a class="dropdown-item" th:href="@{/logout}">退出登录</a>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 页面内容 -->
    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0"><i class="fas fa-plus-circle"></i> 发布二手书</h4>
                    </div>
                    <div class="card-body">
                        <form id="publishForm" enctype="multipart/form-data">
                            <!-- 书名 -->
                            <div class="form-group">
                                <label for="title">书名 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="title" name="title" required>
                            </div>

                            <!-- 作者 -->
                            <div class="form-group">
                                <label for="author">作者</label>
                                <input type="text" class="form-control" id="author" name="author">
                            </div>

                            <!-- 出版社 -->
                            <div class="form-group">
                                <label for="publisher">出版社</label>
                                <input type="text" class="form-control" id="publisher" name="publisher">
                            </div>

                            <!-- ISBN -->
                            <div class="form-group">
                                <label for="isbn">ISBN</label>
                                <input type="text" class="form-control" id="isbn" name="isbn">
                            </div>

                            <!-- 原价 -->
                            <div class="form-group">
                                <label for="originalPrice">原价</label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">¥</span>
                                    </div>
                                    <input type="number" class="form-control" id="originalPrice" name="originalPrice" step="0.01">
                                </div>
                            </div>

                            <!-- 售价 -->
                            <div class="form-group">
                                <label for="price">售价 <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">¥</span>
                                    </div>
                                    <input type="number" class="form-control" id="price" name="price" step="0.01" required>
                                </div>
                            </div>

                            <!-- 成色 -->
                            <div class="form-group">
                                <label for="condition">成色 <span class="text-danger">*</span></label>
                                <select class="form-control" id="condition" name="condition" required>
                                    <option value="1">全新</option>
                                    <option value="2">九成新</option>
                                    <option value="3">八成新</option>
                                    <option value="4">七成新</option>
                                    <option value="5">六成新及以下</option>
                                </select>
                            </div>

                            <!-- 分类 -->
                            <div class="form-group">
                                <label for="category">分类</label>
                                <select class="form-control" id="category" name="category">
                                    <option value="教材教辅">教材教辅</option>
                                    <option value="专业书籍">专业书籍</option>
                                    <option value="文学小说">文学小说</option>
                                    <option value="考试资料">考试资料</option>
                                    <option value="其他">其他</option>
                                </select>
                            </div>

                            <!-- 描述 -->
                            <div class="form-group">
                                <label for="description">描述</label>
                                <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                            </div>

                            <!-- 图片上传 -->
                            <div class="form-group">
                                <label for="image">图片</label>
                                <ul class="nav nav-tabs" id="imageUploadTabs" role="tablist">
                                    <li class="nav-item">
                                        <a class="nav-link active" id="upload-tab" data-toggle="tab" href="#uploadTab" role="tab" aria-controls="upload" aria-selected="true">上传图片</a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" id="local-tab" data-toggle="tab" href="#localTab" role="tab" aria-controls="local" aria-selected="false">本地路径</a>
                                    </li>
                                </ul>
                                <div class="tab-content mt-2" id="imageUploadTabContent">
                                    <div class="tab-pane fade show active" id="uploadTab" role="tabpanel" aria-labelledby="upload-tab">
                                        <input type="file" class="form-control-file" id="imageUpload" name="image" accept="image/*">
                                        <small class="form-text text-muted">支持jpg、png格式，大小不超过2MB</small>
                                    </div>
                                    <div class="tab-pane fade" id="localTab" role="tabpanel" aria-labelledby="local-tab">
                                        <div class="input-group">
                                            <input type="text" class="form-control" id="localImagePath" placeholder="输入本地图片路径，如：C:\Images\book.jpg">
                                            <div class="input-group-append">
                                                <button class="btn btn-outline-secondary" type="button" id="uploadLocalBtn">上传</button>
                                            </div>
                                        </div>
                                        <small class="form-text text-muted">支持jpg、png格式</small>
                                    </div>
                                </div>
                                <input type="hidden" id="imageUrl" name="imageUrl">
                                <div id="uploadProgress" class="progress mt-2" style="display: none;">
                                    <div id="uploadProgressBar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                                </div>
                                <div id="imagePreviewContainer" class="mt-2" style="display: none;">
                                    <img id="imagePreview" class="image-preview" style="max-width: 100%; max-height: 200px;">
                                </div>
                            </div>

                            <!-- 提交按钮 -->
                            <div class="form-group text-center">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-plus-circle"></i> 发布
                                </button>
                                <button type="button" class="btn btn-secondary ml-2" onclick="window.history.back();">
                                    <i class="fas fa-times"></i> 取消
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer th:replace="fragments/footer :: footer"></footer>

    <!-- JavaScript引用 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>
    
    <script th:inline="javascript">
        /*<![CDATA[*/
        $(document).ready(function() {
            // 初始化图片上传
            initImageUpload();
            
            // 表单验证
            $('#publishForm').submit(function(e) {
                e.preventDefault();
                
                // 验证必填字段
                if (!validateForm()) {
                    return;
                }
                
                // 获取表单数据
                var formData = {
                    title: $('#title').val().trim(),
                    author: $('#author').val().trim(),
                    publisher: $('#publisher').val().trim(),
                    isbn: $('#isbn').val().trim(),
                    originalPrice: $('#originalPrice').val(),
                    price: $('#price').val(),
                    condition: $('#condition').val(),
                    category: $('#category').val(),
                    description: $('#description').val().trim(),
                    imageUrl: $('#imageUrl').val()
                };
                
                // 发送请求
                $.ajax({
                    type: 'POST',
                    url: '/booktrading/book/publish',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function(response) {
                        if (response.success) {
                            // 显示成功提示
                            const successAlert = $('<div class="alert alert-success alert-dismissible fade show" role="alert">' +
                                '<strong>恭喜！</strong> 书籍发布成功！' +
                                '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
                                '<span aria-hidden="true">&times;</span></button></div>');
                            
                            $('.card-body').prepend(successAlert);
                            
                            // 2秒后跳转到书籍列表页
                            setTimeout(function() {
                                window.location.href = '/booktrading/book/list';
                            }, 2000);
                        } else {
                            showError('发布失败：' + response.message);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Error:', xhr.responseText);
                        showError('发布失败，请稍后再试');
                    }
                });
            });

            // 价格输入验证
            $('#price, #originalPrice').on('input', function() {
                var value = $(this).val();
                if (value && (isNaN(value) || value < 0)) {
                    $(this).addClass('is-invalid');
                    $(this).next('.invalid-feedback').remove();
                    $(this).after('<div class="invalid-feedback">请输入有效的价格</div>');
                } else {
                    $(this).removeClass('is-invalid');
                    $(this).next('.invalid-feedback').remove();
                }
            });
        });

        // 表单验证函数
        function validateForm() {
            var isValid = true;
            
            // 验证书名
            if (!$('#title').val().trim()) {
                showFieldError('#title', '请输入书名');
                isValid = false;
            } else {
                removeFieldError('#title');
            }
            
            // 验证售价
            var price = $('#price').val();
            if (!price) {
                showFieldError('#price', '请输入售价');
                isValid = false;
            } else if (isNaN(price) || price < 0) {
                showFieldError('#price', '请输入有效的售价');
                isValid = false;
            } else {
                removeFieldError('#price');
            }
            
            // 验证成色
            if (!$('#condition').val()) {
                showFieldError('#condition', '请选择成色');
                isValid = false;
            } else {
                removeFieldError('#condition');
            }
            
            return isValid;
        }

        // 显示字段错误
        function showFieldError(fieldId, message) {
            $(fieldId).addClass('is-invalid');
            $(fieldId).next('.invalid-feedback').remove();
            $(fieldId).after('<div class="invalid-feedback">' + message + '</div>');
        }

        // 移除字段错误
        function removeFieldError(fieldId) {
            $(fieldId).removeClass('is-invalid');
            $(fieldId).next('.invalid-feedback').remove();
        }

        // 显示错误消息
        function showError(message) {
            var errorAlert = '<div class="alert alert-danger alert-dismissible fade show" role="alert">' +
                message +
                '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
                '<span aria-hidden="true">&times;</span></button></div>';
            
            $('.card-body').prepend(errorAlert);
        }

        // 图片上传预览
        function initImageUpload() {
            $('#imageUpload').change(function() {
                const file = this.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        $('#imagePreview').attr('src', e.target.result);
                        $('#imagePreviewContainer').show();
                    }
                    reader.readAsDataURL(file);
                    
                    // 上传图片
                    uploadImage(file);
                }
            });
            
            // 本地路径上传
            $('#uploadLocalBtn').click(function() {
                const localPath = $('#localImagePath').val().trim();
                if (localPath) {
                    uploadFromLocalPath(localPath);
                } else {
                    showError('请输入本地图片路径');
                }
            });
        }

        // 图片上传函数
        function uploadImage(file) {
            const formData = new FormData();
            formData.append('file', file);
            
            // 显示上传进度
            $('#uploadProgress').show();
            
            $.ajax({
                type: 'POST',
                url: '/booktrading/book/upload-image',
                data: formData,
                processData: false,
                contentType: false,
                xhr: function() {
                    const xhr = new window.XMLHttpRequest();
                    xhr.upload.addEventListener("progress", function(evt) {
                        if (evt.lengthComputable) {
                            const percentComplete = evt.loaded / evt.total * 100;
                            $('#uploadProgressBar').width(percentComplete + '%');
                        }
                    }, false);
                    return xhr;
                },
                success: function(response) {
                    if (response.success) {
                        $('#imageUrl').val(response.imageUrl);
                        $('#uploadProgress').hide();
                    } else {
                        showError(response.message);
                        $('#uploadProgress').hide();
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error:', xhr.responseText);
                    showError('图片上传失败，请稍后再试');
                    $('#uploadProgress').hide();
                }
            });
        }
        
        // 从本地路径上传图片
        function uploadFromLocalPath(localPath) {
            // 显示上传进度
            $('#uploadProgress').show();
            $('#uploadProgressBar').width('50%');
            
            $.ajax({
                type: 'POST',
                url: '/booktrading/book/upload-image-from-local',
                data: {
                    path: localPath
                },
                success: function(response) {
                    if (response.success) {
                        $('#imageUrl').val(response.imageUrl);
                        // 显示图片预览
                        $('#imagePreview').attr('src', response.imageUrl);
                        $('#imagePreviewContainer').show();
                        $('#uploadProgress').hide();
                    } else {
                        showError(response.message);
                        $('#uploadProgress').hide();
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error:', xhr.responseText);
                    showError('图片上传失败，请稍后再试');
                    $('#uploadProgress').hide();
                }
            });
        }
        /*]]>*/
    </script>
</body>
</html> 